﻿/**
 * 通用js方法封装处理
 * Copyright (c) 2019 enjoy
 */
import moment from 'moment'


export function format(date, format){
  return moment(date).format(format)
}

// 解析导出的二进制文件流
export function isExcel(type,name, data) {
  const link = document.createElement('a')
  const blob = new Blob([data],{type:type})
  link.style.display = 'none'
  link.href = URL.createObjectURL(blob)
  link.download = name;
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm),'');
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

// 日期
export function getDate() {
  return new Date().toLocaleDateString().replace(/\//g, '-')
}

// 表单重置
export function resetForm(refName) {
	if (this.$refs[refName]) {
		this.$refs[refName].resetFields();
	}
}

// 添加日期范围
export function addDateRange(params, dateRange, propName, self) {
	let search = params;
	search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
	dateRange = Array.isArray(dateRange) ? dateRange : [];
	if (typeof (propName) === 'undefined') {
		search.params['beginTime'] = dateRange[0];
		search.params['endTime'] = dateRange[1];
	} else {
    if(self){
      search.params[self.filed[0]] = dateRange[0];
      search.params[self.filed[1]] = dateRange[1];
    }else{
      search.params['begin' + propName] = dateRange[0];
		  search.params['end' + propName] = dateRange[1];
    }
	}
	return search;
}

// 回显数据字典
export function selectDictLabel(datas, value) {
	var actions = [];
	Object.keys(datas).some((key) => {
		if (datas[key].value == ('' + value)) {
			actions.push(datas[key].label);
			return true;
		}
	})
	return actions.join('');
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
	var actions = [];
	var currentSeparator = undefined === separator ? "," : separator;
	var temp = value.split(currentSeparator);
	Object.keys(value.split(currentSeparator)).some((val) => {
		Object.keys(datas).some((key) => {
			if (datas[key].value == ('' + temp[val])) {
				actions.push(datas[key].label + currentSeparator);
			}
		})
	})
	return actions.join('').substring(0, actions.join('').length - 1);
}

// 字符串格式化(%s )
export function sprintf(str) {
	var args = arguments, flag = true, i = 1;
	str = str.replace(/%s/g, function () {
		var arg = args[i++];
		if (typeof arg === 'undefined') {
			flag = false;
			return '';
		}
		return arg;
	});
	return flag ? str : '';
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty(str) {
	if (!str || str == "undefined" || str == "null") {
		return "";
	}
	return str;
}

// 数据合并
export function mergeRecursive(source, target) {
    for (var p in target) {
        try {
            if (target[p].constructor == Object) {
                source[p] = mergeRecursive(source[p], target[p]);
            } else {
                source[p] = target[p];
            }
        } catch(e) {
            source[p] = target[p];
        }
    }
    return source;
};

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
	let config = {
		id: id || 'id',
		parentId: parentId || 'parentId',
		childrenList: children || 'children'
	};

	var childrenListMap = {};
	var nodeIds = {};
	var tree = [];

	for (let d of data) {
		let parentId = d[config.parentId];
		if (childrenListMap[parentId] == null) {
			childrenListMap[parentId] = [];
		}
		nodeIds[d[config.id]] = d;
		childrenListMap[parentId].push(d);
	}

	for (let d of data) {
		let parentId = d[config.parentId];
		if (nodeIds[parentId] == null) {
			tree.push(d);
		}
	}

	for (let t of tree) {
		adaptToChildrenList(t);
	}

	function adaptToChildrenList(o) {
		if (childrenListMap[o[config.id]] !== null) {
			o[config.childrenList] = childrenListMap[o[config.id]];
		}
		if (o[config.childrenList]) {
			for (let c of o[config.childrenList]) {
				adaptToChildrenList(c);
			}
		}
	}
	return tree;
}

// 格式化 值 -> 内容
export function formatValuesToText(list, value) {
  let temp = ''
  if (value !== null && value !== '') {
    for (const index in list) {
      if (Number(list[index].value) === Number(value)) {
        temp = list[index].text || list[index].label
        break
      }
    }
  }
  return temp
}

// 通用拼接
export function joinText(value, value2) {
  return `${value} - ${value2}`
}

// 根据ProjectId获取聚焦节点ID
export function getFocusIdByProjectId(projectId) {
  return this.$store.state.fmea.projectFocusId[projectId]
}

// 设置聚焦节点
export function setProjectFocusId(projectId, structureId) {
  this.$store.dispatch('fmea/SetProjectFocusId', { projectId, structureId })
}

/**
 * 设置项目是否可编辑
 */
export function setProjectIfEdit(versionStatus, handleEnable, handleDisable) {
  if (versionStatus === this.$store.state.fmea.projectVersionStatus[0].value) {
    if (handleEnable) {
      handleEnable()
    }
    this.commitProjectIfEdit(true)
  } else {
    if (handleDisable) {
      handleDisable()
    }
    this.commitProjectIfEdit(false)
  }
}
export function commitProjectIfEdit(val) {
  this.$store.commit('fmea/SET_PROJECT_IF_EDIT', val)
}

/**
 * 获取可视内容高度
 */
export function getContentHeight() {
  // 菜单栏 64 Tab 44 底部 24
  return document.body.clientHeight - 50 - 34 - 5
}

/**
 * 获取树形组件里的颜色、图标
 */
export function getColor(nodeType, nodeTypes) {
  let colorObj = {}
  for (const k in nodeTypes) {
    if (nodeType === Number(k)) {
      colorObj = nodeTypes[k]
      break
    }
  }
  return colorObj
}

export function getIcon(nodeRelation, colorObj) {
  if (nodeRelation === 0) {
    return colorObj.noneIcon
  } else if (nodeRelation === 1) {
    return colorObj.leftIcon
  } else if (nodeRelation === 2) {
    return colorObj.rightIcon
  } else if (nodeRelation === 3) {
    return colorObj.fullIcon
  }
}

/**
 * 删除vxe选中行
 */
export function removeChecked(xTable, dataTable, keyname, user) {
  let checkedItems = xTable.getCheckboxRecords()
  if (user === 'expert') {
    const expertRoles = ['制造代表', '试制工程师', '产品质量工程师']
    let msg = ''
    checkedItems = checkedItems.filter(res => {
      const index = expertRoles.indexOf(res.post)
      if (index > -1 && !msg.includes(expertRoles[index])) { msg = msg + '"' + expertRoles[index] + '" ' }
      return index === -1
    })
    if (msg) { Message.error('不可删除 ' + msg + '!') }
  }
  checkedItems.forEach(item => {
    dataTable = dataTable.filter(res => {
      return res[keyname] !== item[keyname]
    })
  }, this)
  return dataTable
}

/**
 * 删除vxe当前行
 */
export function deleteChecked(index, dataTable, keyname, user) {
  if (user === 'expert') {
    const expertRoles = ['制造代表', '试制工程师', '产品质量工程师']
    let msg = ''
    const row = dataTable[index]
    const typeIndex = expertRoles.indexOf(row.post)
    if(typeIndex> -1 && !msg.includes(expertRoles[typeIndex])){
      msg = msg + '"' + expertRoles[typeIndex] + '" '
    }
    if (msg) { Message.error('不可删除 ' + msg + '!');return; }
  }
  dataTable.splice(index,1)
  return dataTable
}

/**
 * 单元格激活时
 */
export function editActived(actRow, k1, k2) {
  let curVal = actRow.row[k1]
  if (k2) {
    curVal = actRow.row[k1][k2]
  }
  if (curVal) {
    return { rowIndex: actRow.rowIndex, operate: 'edit' }
  } else {
    return { rowIndex: actRow.rowIndex, operate: 'add' }
  }
}

/**
 * 处理 path
 */
export function handlePath(routePath) {
  if (!routePath.includes('?')) {
    let path = '/index'
    if (routePath !== '/index') {
      path = routePath.split('/index')[0]
    }
    return path
  } else {
    let path = routePath.split('?')[0]
    if (path.includes('/index')) {
      path = path.split('/index')[0]
    }
    return path
  }
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
	let result = ''
	for (const propName of Object.keys(params)) {
		const value = params[propName];
		var part = encodeURIComponent(propName) + "=";
		if (value !== null && typeof (value) !== "undefined") {
			if (typeof value === 'object') {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && typeof (value[key]) !== 'undefined') {
						let params = propName + '[' + key + ']';
						var subPart = encodeURIComponent(params) + "=";
						result += subPart + encodeURIComponent(value[key]) + "&";
					}
				}
			} else {
				result += part + encodeURIComponent(value) + "&";
			}
		}
	}
	return result
}

// 验证是否为blob格式
export async function blobValidate(data) {
    try {
      let text = await data.text();
      text = JSON.parse(text);
      data.msg = text.msg
      return false;
    } catch (error) {
      return true;
    }
}

/**
 * 项目组织产线
 */
export async function storeOrgPline(data) {
  this.$store.commit('fmea/SET_PROJECT_ORG', data.organizeId)
  let productLineIds = [0]
  if ([1, 7, 8].includes(data.businessScenario)) {
    await getProjProdList(this.projectId).then(response => {
      if (response.data) {
        response.data.forEach(item => {
          if (item.productLineId) { productLineIds.push(item.productLineId) }
        })
      }
    })
  } else if ([2].includes(data.businessScenario)) {
    await getProjProdClassList(this.projectId).then(response => {
      if (response.data) {
        response.data.forEach(item => {
          if (item.productLineId) { productLineIds.push(item.productLineId) }
        })
      }
    })
  }
  productLineIds = Array.from(new Set(productLineIds))
  this.$store.commit('fmea/SET_PROJECT_PLINE', productLineIds)
}

/**
 * 进度排序
 */
export function progressSort(progress, actTaskName) {
  const approved = []
  const pendingApproval = []
  const curUserPendingApproval = []
  const curPendingApproval = []
  const userPendingApproval = []
  progress.forEach(item => {
    if (item.reviewStatus === 1 || item.reviewStatus === 2) {
      approved.push(item)
      approved.sort((a, b) => {
        const timeStampA = new Date(a.updateTime).getTime()
        const timeStampB = new Date(b.updateTime).getTime()
        return timeStampA - timeStampB
      })
    } else if (item.reviewStatus === 0) {
      if (item.reviewNode === actTaskName) {
        if (item.reviewUserId === this.$store.state.user.userId) {
          curUserPendingApproval.push(item)
        } else {
          curPendingApproval.push(item)
        }
      } else if (item.reviewUserName === this.$store.state.user.name) {
        userPendingApproval.push(item)
      } else {
        pendingApproval.push(item)
      }
    }
  })
  progress = [...approved, ...curUserPendingApproval, ...curPendingApproval, ...userPendingApproval, ...pendingApproval]
  return progress
}

/**
 * 水印
 */
export function getWatermarkInfo() {
  getWatermark().then(res => {
    this.$store.commit('fmea/SET_WATER_MARK', res.msg)
    watermark.set(res.msg)
  })
}
